package metodos;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import requisicao.Parametro;
import requisicao.Requisicao;

public class Post extends Metodo {

	private InputStream in;
	private String dados = null;
	
	public Post(Requisicao requisicao) {
		super(requisicao);
		in = requisicao.getIn();
		executa();
		parametros.setTemParametros(true);
	}

	@Override
	protected void executa() {
		receberParametros();
		definirParametros();
	}
	private void receberParametros(){
		if(Integer.parseInt(requisicao.getCabecalho().getValor("Content-Length").trim())>0){			
			byte[] buffer = new byte[Integer.parseInt(requisicao.getCabecalho().getValor("Content-Length").trim())];
			
			try {
				in.read(buffer,0,Integer.parseInt(requisicao.getCabecalho().getValor("Content-Length").trim()));
				dados = new String(buffer, "UTF-8");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			try {
				dados = java.net.URLDecoder.decode(dados, "UTF-8");
			} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}		
	}
	public  String lerDados()
	{
		BufferedInputStream bis = new BufferedInputStream(in);
	    ByteArrayOutputStream buf = new ByteArrayOutputStream();
	    int result;
		try {
			result = bis.read();
			while(result != -1) {
			      byte b = (byte)result;
			      buf.write(b);
			      result = bis.read();
			    } 
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	           
	    return buf.toString();
	}

	private void definirParametros() {
		if(dados!=null){
			String[] geral = dados.split("&");
			String[] partes;
			for (String string : geral) {
				partes = string.split("=");
				parametros.addParametro(partes[0], partes[1]);
			}
		}		
	}

	@Override
	public Parametro getParametros() {
		return parametros;
	}
}
